package main

import (
	"fmt"
	"time"
)

//取得当前月份的起始日期
func main() {

	//t := time.Now()
	//dateFormat := "2006-01-02"
	//
	//fmt.Println(BeginningOfMonth(t).Format(dateFormat)) //2022-07-01
	//fmt.Println(EndOfMonth(t).Format(dateFormat))       //2022-07-31

	b := str2Time("2021-08-01 16:54:20")

	if checkIsOneYearInterval(b) {
		fmt.Println("一年之内")
	} else {
		fmt.Println("大于一年了")
	}
}

func str2Time(timeStr string) time.Time {
	pattern := "2006-01-02 15:04:05"

	var dt time.Time
	//loc, _ := time.LoadLocation("Asia/Shanghai")
	//dt, err := time.ParseInLocation(pattern, timeStr, loc)
	dt, err := time.Parse(pattern, timeStr)

	//dt, err := time.Parse(pattern, timeStr)
	if err != nil {
		fmt.Printf("have err %v:", err)
	}
	return dt
}

//判断时间跨度是否在一年之内，一年之内返回true,超过一年返回false
func checkIsOneYearInterval(beginDate time.Time) bool {
	var ms int64 = 31536000000             // 365天的毫秒数
	sub := time.Now().Sub(beginDate) / 1e6 //转换为毫秒数
	//如果天数大于366天或者小于1天，一定属于不合法输入，返回false
	if sub > 31622400000 || sub < 0 {
		return false
	}

	beginYear := beginDate.Year()
	beginMonth := beginDate.Month()

	dueYear := time.Now().Year()
	dueMonth := time.Now().Month()

	//判断是否是闰年，并且跨过2月，则增加一天的毫秒数
	if isLeapYear(beginYear) && beginMonth <= 2 {
		ms += 86400000
	} else if isLeapYear(dueYear) && dueMonth >= 2 {
		ms += 86400000
	}

	return int64(sub) <= ms
}

// isLeapYear 判断年份是否为闰年
func isLeapYear(year int) bool {
	if year%100 == 0 {
		if year%400 == 0 {
			return true
		}
	} else if year%4 == 0 {
		return true
	}
	return false
}

func monthInterval(year int, month time.Month) (firstDay, lastDay time.Time) {
	firstDay = time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)
	lastDay = time.Date(year, month+1, 1, 0, 0, 0, -1, time.UTC)
	return firstDay, lastDay
}

func BeginningOfMonth(t time.Time) time.Time {
	return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}

func EndOfMonth(t time.Time) time.Time {
	return BeginningOfMonth(t).AddDate(0, 1, 0).Add(-time.Second)
}

func timeInterval() {
	fmt.Printf("时间戳（秒）：%v;\n", time.Now().Unix())
	fmt.Printf("时间戳（纳秒）：%v;\n", time.Now().UnixNano())
	fmt.Printf("时间戳（毫秒）：%v;\n", time.Now().UnixNano()/1e6)
	fmt.Printf("时间戳（纳秒转换为秒）：%v;\n", time.Now().UnixNano()/1e9)

}
